<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>物流订单管理系统</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <!-- 引入主题CSS -->
    <link rel="stylesheet" href="/css/theme.css">

    <!-- 高德地图 JS API 引入 -->
    <script type="text/javascript"
            src="https://webapi.amap.com/maps?v=2.0&key=c1c30b5cd6070eb5d55dbb33ce06d372"></script>

    <style>
        /* 为地图容器预留样式 */
        #mapContainer {
            width: 100%;
            height: 450px;
            border-radius: var(--border-radius);
            border: 1px solid var(--border-color);
            margin-top: 20px;
        }
        
        .container-main {
            margin-top: 20px;
            background-color: var(--card-bg);
            padding: 30px;
            border-radius: var(--border-radius);
            box-shadow: var(--box-shadow);
        }
        
        .section-title {
            font-size: 1.75rem;
            font-weight: 500;
            margin-bottom: 25px;
            padding-bottom: 10px;
            border-bottom: 1px solid var(--border-color);
            display: flex;
            align-items: center;
        }
    </style>
</head>
<body>

<!-- 将导航栏从navbar-light bg-light改为navbar-dark bg-primary -->
<nav class="navbar navbar-expand-lg navbar-dark bg-primary sticky-top">
    <div class="container-fluid">
        <a class="navbar-brand" href="#"><i class="bi bi-truck me-2"></i>物流订单管理系统</a>
        <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation">
            <span class="navbar-toggler-icon"></span>
        </button>
        <div class="collapse navbar-collapse" id="navbarNav">
            <ul class="navbar-nav me-auto"> <!-- 修改为me-auto使导航项靠左 -->
                <!-- 主导航项 -->
                <li class="nav-item">
                    <a class="nav-link" href="#orderQuerySection"><i class="bi bi-search"></i>订单查询</a>
                </li>
                <li class="nav-item">
                    <a class="nav-link" href="/profile.html"><i class="bi bi-person me-1"></i>个人中心</a>
                </li>
            </ul>
            
            <ul class="navbar-nav ms-auto">
                <!-- 订单创建按钮 - 后续可以根据登录状态控制 -->
                <li class="nav-item me-2"> <!-- Added me-2 for spacing -->
                    <button class="btn btn-success" id="triggerCreateOrderModalButton">
                        <i class="bi bi-plus-circle-fill me-1"></i> 创建新订单
                    </button>
                </li>

                <!-- 用户认证相关链接将动态添加到这里 -->
                <li class="nav-item" id="authLinksContainer">
                    <!-- 初始状态：显示登录链接 -->
                    <a class="btn btn-primary" href="/login.html">登录</a>
                </li>
                <li class="nav-item dropdown" id="userDropdownContainer" style="display: none;">
                    <a class="nav-link dropdown-toggle" href="#" id="userDropdown" role="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bi bi-person-circle me-1"></i> <span id="usernameDisplay">用户</span>
                    </a>
                    <ul class="dropdown-menu dropdown-menu-end" aria-labelledby="userDropdown">
                        <li><a class="dropdown-item" href="/profile.html"><i class="bi bi-person me-2"></i>个人中心</a></li>
                        <li><a class="dropdown-item" href="#" id="logoutButton"><i class="bi bi-box-arrow-right me-2"></i>登出</a></li>
                        <!-- 可以添加其他用户相关链接，如"我的订单"，"修改密码"等 -->
                    </ul>
                </li>
            </ul>
        </div>
    </div>
</nav>

<!-- 个性化欢迎信息 -->
<div class="alert alert-success alert-dismissible fade show m-0" id="welcomeMessage" style="display: none; border-radius: 0;">
    <div class="container d-flex align-items-center">
        <i class="bi bi-emoji-smile fs-4 me-2"></i>
        <div>
            <span id="welcomeText">欢迎回来！</span>
        </div>
        <button type="button" class="btn-close ms-auto" data-bs-dismiss="alert" aria-label="Close"></button>
    </div>
</div>

<div class="container container-main">
    <section id="orderQuerySection" class="mb-5">
        <h2 class="section-title"><i class="bi bi-search"></i>订单查询</h2>
        <div class="row g-3 align-items-center">
            <div class="col-md">
                <input type="text" class="form-control form-control-lg" id="orderNumberInput" placeholder="请输入订单号进行查询">
            </div>
            <div class="col-md-auto">
                <button class="btn btn-primary btn-lg w-100" id="trackOrderButton">
                    <i class="bi bi-arrow-right-circle-fill me-1"></i> 查询
                </button>
            </div>
        </div>
    </section>

    <div id="loader" class="spinner-container" style="display: none;">
        <div class="spinner-border text-primary" style="width: 3rem; height: 3rem;" role="status">
            <span class="visually-hidden">Loading...</span>
        </div>
    </div>

    <div id="alertMessage" class="mt-4"></div>

    <div class="row g-4">
        <div class="col-lg-5" id="orderInfoColumn" style="display: none;">
            <section id="orderInfoSection">
                <h3 class="section-title"><i class="bi bi-box-seam"></i>订单详情</h3>
                <div id="orderDetails" class="card"><div class="card-body"></div></div>
            </section>
        </div>
        <div class="col-lg-7" id="logisticsTraceAndMapColumn" style="display: none;">
            <section id="logisticsTraceSection">
                <h3 class="section-title"><i class="bi bi-geo-alt-fill"></i>物流追踪</h3>
                <div id="logisticsTrace" class="card">
                    <div class="card-body"><p>暂无物流信息。</p></div>
                </div>
            </section>

            <section id="mapDisplaySection" class="mt-4" style="display: none;">
                <h3 class="section-title"><i class="bi bi-map-fill"></i>配送路径</h3>
                <div id="mapContainer"></div>
            </section>
        </div>
    </div>
</div>

<div class="modal fade" id="createOrderModal" tabindex="-1" aria-labelledby="createOrderModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-lg modal-dialog-scrollable">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title" id="createOrderModalLabel"><i class="bi bi-pencil-square me-2"></i>创建新订单</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
            </div>
            <div class="modal-body">
                <form id="createOrderForm">
                    <h6><i class="bi bi-person-up me-1"></i>发货人信息</h6>
                    <!-- 发货人地址部分 -->
                    <div class="row g-3 mb-4">
                        <div class="col-md-6"><label for="shipperNameM" class="form-label">姓名</label><input type="text" class="form-control" id="shipperNameM" required></div>
                        <div class="col-md-6"><label for="shipperPhoneM" class="form-label">电话</label><input type="tel" class="form-control" id="shipperPhoneM" required></div>
                        <div class="col-md-4">
                            <label for="shipperProvinceM" class="form-label">省份</label>
                            <select class="form-select" id="shipperProvinceM" required>
                                <option value="">请选择省份</option>
                                <!-- 省份选项将通过JavaScript动态添加 -->
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="shipperCityM" class="form-label">城市</label>
                            <select class="form-select" id="shipperCityM" required>
                                <option value="">请选择城市</option>
                                <!-- 城市选项将通过JavaScript动态添加 -->
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="shipperDistrictM" class="form-label">区域</label>
                            <select class="form-select" id="shipperDistrictM">
                                <option value="">请选择区域</option>
                                <!-- 区域选项将通过JavaScript动态添加 -->
                            </select>
                        </div>
                        <div class="col-12 d-flex justify-content-between align-items-center">
                            <label for="shipperDetailAddressM" class="form-label">详细地址</label>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="showAddressSelector('shipper')">选择常用地址</button>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="saveUserAddress('shipper')">保存为常用地址</button>
                            </div>
                        </div>
                        <div class="col-12"><input type="text" class="form-control" id="shipperDetailAddressM" required></div>
                    </div>
                    
                    <!-- 收货人地址部分 -->
                    <div class="row g-3 mb-4">
                        <div class="col-md-6"><label for="recipientNameM" class="form-label">姓名</label><input type="text" class="form-control" id="recipientNameM" required></div>
                        <div class="col-md-6"><label for="recipientPhoneM" class="form-label">电话</label><input type="tel" class="form-control" id="recipientPhoneM" required></div>
                        <div class="col-md-6">
                            <label for="recipientEmailM" class="form-label">邮箱（可选）</label>
                            <div class="email-selection-container">
                                <select class="form-select" id="recipientEmailSelect">
                                    <option value="">选择已保存的邮箱</option>
                                    <option value="manual">手动输入</option>
                                </select>
                                <input type="email" class="form-control" id="recipientEmailM" placeholder="example@email.com" style="display: none;">
                                <div class="selected-email-display" id="selectedEmailDisplay" style="display: none;">
                                    <div class="input-group">
                                        <input type="email" class="form-control" id="displayEmailInput" readonly>
                                        <button class="btn btn-outline-secondary" type="button" id="changeEmailBtn">
                                            <i class="bi bi-pencil"></i> 更换
                                        </button>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="form-check mt-4">
                                <input class="form-check-input" type="checkbox" id="recipientEmailNotificationM">
                                <label class="form-check-label" for="recipientEmailNotificationM">
                                    接收邮件通知
                                </label>
                            </div>
                        </div>
                        <div class="col-md-4">
                            <label for="recipientProvinceM" class="form-label">省份</label>
                            <select class="form-select" id="recipientProvinceM" required>
                                <option value="">请选择省份</option>
                                <!-- 省份选项将通过JavaScript动态添加 -->
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="recipientCityM" class="form-label">城市</label>
                            <select class="form-select" id="recipientCityM" required>
                                <option value="">请选择城市</option>
                                <!-- 城市选项将通过JavaScript动态添加 -->
                            </select>
                        </div>
                        <div class="col-md-4">
                            <label for="recipientDistrictM" class="form-label">区域</label>
                            <select class="form-select" id="recipientDistrictM">
                                <option value="">请选择区域</option>
                                <!-- 区域选项将通过JavaScript动态添加 -->
                            </select>
                        </div>
                        <div class="col-12 d-flex justify-content-between align-items-center">
                            <label for="recipientDetailAddressM" class="form-label">详细地址</label>
                            <div>
                                <button type="button" class="btn btn-sm btn-outline-secondary me-2" onclick="showAddressSelector('recipient')">选择常用地址</button>
                                <button type="button" class="btn btn-sm btn-outline-primary" onclick="saveUserAddress('recipient')">保存为常用地址</button>
                            </div>
                        </div>
                        <div class="col-12"><input type="text" class="form-control" id="recipientDetailAddressM" required></div>
                    </div>
                    <h6><i class="bi bi-box me-1"></i>物品信息</h6>
                    <div class="row g-3">
                        <div class="col-md-8"><label for="itemDescriptionM" class="form-label">物品描述</label><input type="text" class="form-control" id="itemDescriptionM" required></div>
                        <div class="col-md-4"><label for="weightM" class="form-label">重量 (kg)</label><input type="number" class="form-control" id="weightM" step="0.01" min="0.01" required></div>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button>
                <button type="submit" class="btn btn-primary" form="createOrderForm"><i class="bi bi-check-circle-fill me-1"></i>提交订单</button>
            </div>
        </div>
    </div>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js"></script>
<script>
    // --- DOM Elements ---
    const orderNumberInput = document.getElementById('orderNumberInput');
    const trackOrderButton = document.getElementById('trackOrderButton');
    const orderDetailsDiv = document.getElementById('orderDetails').querySelector('.card-body');
    const logisticsTraceCardBody = document.getElementById('logisticsTrace').querySelector('.card-body');
    const alertMessageDiv = document.getElementById('alertMessage');
    const orderInfoColumn = document.getElementById('orderInfoColumn');
    const logisticsTraceAndMapColumn = document.getElementById('logisticsTraceAndMapColumn');
    const loaderDiv = document.getElementById('loader');

    // Map Elements
    const mapContainerDiv = document.getElementById('mapContainer');
    const mapDisplaySection = document.getElementById('mapDisplaySection');
    let mapInstance = null;

    // Create Order Modal Elements
    const triggerCreateOrderModalButton = document.getElementById('triggerCreateOrderModalButton');
    const createOrderModalElement = document.getElementById('createOrderModal');
    const createOrderForm = document.getElementById('createOrderForm');
    let createOrderModalInstance = null;

    // Auth Elements (from Navbar)
    const authLinksContainer = document.getElementById('authLinksContainer');
    const userDropdownContainer = document.getElementById('userDropdownContainer');
    const usernameDisplay = document.getElementById('usernameDisplay');
    const logoutButton = document.getElementById('logoutButton');
  
    // 修改为
    const API_BASE_URL = '/api/v1';
    const AUTH_API_URL = 'http://localhost:8080/api/v1/auth'; // For registration, if needed

    // --- Initialize ---
    document.addEventListener('DOMContentLoaded', () => {
        createOrderModalInstance = new bootstrap.Modal(createOrderModalElement);
        checkLoginStatusAndUpdateUI(); // Check login status on page load

        // Re-bind logout button event listener here after DOM is ready and elements are defined
        if (logoutButton) {
            logoutButton.addEventListener('click', handleLogout);
        }
        
        // 初始化邮箱选择功能
        initializeEmailSelection();
    });

    // --- Event Listeners ---
    trackOrderButton.addEventListener('click', handleTrackOrder);
    orderNumberInput.addEventListener('keypress', (event) => {
        if (event.key === 'Enter') handleTrackOrder();
    });
    triggerCreateOrderModalButton.addEventListener('click', () => {
        // We might want to check if user is logged in before showing modal,
        // or disable the button if not logged in (handled by checkLoginStatusAndUpdateUI)
        createOrderForm.reset();
        clearAlert();
        createOrderModalInstance.show();
    });
    createOrderForm.addEventListener('submit', handleCreateOrder);


    // --- Helper Functions ---
    function showLoader(show) { loaderDiv.style.display = show ? 'flex' : 'none'; }
    function clearAlert() { alertMessageDiv.innerHTML = ''; }

    function clearQueryResults() {
        orderDetailsDiv.innerHTML = '';
        logisticsTraceCardBody.innerHTML = '<p>暂无物流信息。</p>';
        orderInfoColumn.style.display = 'none';
        logisticsTraceAndMapColumn.style.display = 'none';
        if (mapInstance) {
            mapInstance.destroy();
            mapInstance = null;
        }
        mapContainerDiv.innerHTML = '';
        mapDisplaySection.style.display = 'none';
        clearAlert();
    }

    function showAlert(message, type = 'info', isHtml = false) {
        const alertDiv = document.createElement('div');
        alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
        alertDiv.setAttribute('role', 'alert');
        let iconClass = 'bi-info-circle-fill';
        if (type === 'danger') iconClass = 'bi-exclamation-triangle-fill';
        else if (type === 'success') iconClass = 'bi-check-circle-fill';

        if (isHtml) {
            alertDiv.innerHTML = `<i class="bi ${iconClass} me-2"></i>${message}<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>`;
        } else {
            alertDiv.textContent = message; // Default to textContent for security
            // If you still want the icon with textContent, you'd have to build it more manually
            alertDiv.innerHTML = `<i class="bi ${iconClass} me-2"></i>${message}<button type="button" class="btn-close" data-bs-dismiss="alert" aria-label="Close"></button>`;
        }
        alertMessageDiv.innerHTML = ''; // Clear previous alerts
        alertMessageDiv.appendChild(alertDiv);
    }

    function formatDate(dateString) {
        if (!dateString) return 'N/A';
        const date = new Date(dateString);
        if (isNaN(date.getTime())) return dateString; // Return original if invalid
        return date.toLocaleString('zh-CN', {
            year: 'numeric', month: '2-digit', day: '2-digit',
            hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false
        });
    }

    function formatOrderStatus(status) {
        const statusMap = {"PENDING_PICKUP": "待揽收", "IN_TRANSIT": "运输中", "OUT_FOR_DELIVERY": "派送中", "DELIVERED": "已签收", "CANCELLED": "已取消", "EXCEPTION": "异常件", "PENDING_COLLECTION": "待揽收", "COLLECTED": "已揽件", "TRANSPORTING": "运输中", "SIGNED": "已签收", "COMPLETED": "已完成", "DELIVERY_FAILED": "派送失败", "PENDING_PAYMENT": "等待付款"};
        return statusMap[status] || status;
    }

    function formatLogisticsStatus(status) {
        const statusMap = {"ORDER_PLACED": "订单已创建", "PICKED_UP": "已揽收", "COLLECTED": "已揽件", "PENDING_COLLECTION":"待揽收", "WAREHOUSED":"已入库", "TRANSPORTING":"运输中", "ARRIVED_HUB": "到达分拣中心", "DEPARTED_HUB": "离开分拣中心", "OUT_FOR_DELIVERY": "开始派送", "DELIVERED_SUCCESS": "成功送达", "DELIVERY_FAILED": "派送失败", "SIGNED": "已签收", "CANCELLED":"已取消", "UNKNOWN":"未知状态"};
        return statusMap[status] || status;
    }

    // --- Authentication Related Functions ---
    // 显示个性化欢迎信息
    function displayWelcomeMessage(username) {
        const welcomeMessage = document.getElementById('welcomeMessage');
        const welcomeText = document.getElementById('welcomeText');
        
        if (welcomeMessage && welcomeText) {
            // 根据时间生成不同的欢迎语
            const hour = new Date().getHours();
            let greeting = '';
            
            if (hour < 6) {
                greeting = '夜深了，';
            } else if (hour < 9) {
                greeting = '早上好，';
            } else if (hour < 12) {
                greeting = '上午好，';
            } else if (hour < 14) {
                greeting = '中午好，';
            } else if (hour < 18) {
                greeting = '下午好，';
            } else if (hour < 22) {
                greeting = '晚上好，';
            } else {
                greeting = '夜深了，';
            }
            
            welcomeText.textContent = `${greeting}${username}！欢迎回到物流订单管理系统`;
            welcomeMessage.style.display = 'block';
        }
    }
    
    // 在检查登录状态的函数中调用欢迎信息显示
    async function checkLoginStatusAndUpdateUI() {
        try {
            const response = await fetch(`${API_BASE_URL}/orders/me`);
            if (response.ok) {
                const user = await response.json();
                console.log('User logged in:', user);
                
                // 检查用户是否为配送员角色
                if (user.roles && Array.isArray(user.roles)) {
                    for (let i = 0; i < user.roles.length; i++) {
                        const role = user.roles[i];
                        if (role.authority === 'ROLE_DELIVERY_PERSON') {
                            console.log('配送员角色检测到，正在重定向到配送员界面...');
                            window.location.href = '/delivery.html';
                            return; // 重定向后不继续执行
                        }
                    }
                }
                
                // 普通用户界面显示逻辑
                displayLoggedInUI(user);
                // 显示欢迎信息
                displayWelcomeMessage(user.username);
                
            } else if (response.status === 401) {
                console.log('User not logged in (401).');
                displayLoggedOutUI();
            } else {
                console.warn('Error checking login status, server responded with:', response.status);
                displayLoggedOutUI();
            }
        } catch (error) {
            console.error('Network error or other issue checking login status:', error);
            displayLoggedOutUI();
        }
    }

    // 在displayLoggedInUI函数中添加调用
    function displayLoggedInUI(user) {
        if (authLinksContainer) authLinksContainer.style.display = 'none';
        if (userDropdownContainer) userDropdownContainer.style.display = 'block';
        if (usernameDisplay) usernameDisplay.textContent = user.username;
        if (triggerCreateOrderModalButton) triggerCreateOrderModalButton.style.display = 'inline-block';
        
        // 加载用户最近订单
        loadLatestUserOrder();
    }
    
    // 添加获取最近订单的函数
    async function loadLatestUserOrder() {
        try {
            const response = await fetch(`${API_BASE_URL}/orders/latest`);
            
            if (response.status === 204) {
                // 没有订单
                console.log('用户没有订单');
                return;
            }
            
            if (!response.ok) {
                console.warn('获取最近订单失败:', response.status);
                return;
            }
            
            const latestOrder = await response.json();
            console.log('获取到最近订单:', latestOrder);
            
            // 显示最近订单区域
            const latestOrderSection = document.getElementById('latestOrderSection');
            if (latestOrderSection) latestOrderSection.style.display = 'block';
            
            // 填充订单详情
            document.getElementById('latestOrderNumber').textContent = latestOrder.orderNumber;
            document.getElementById('latestOrderDescription').textContent = latestOrder.itemDescription;
            document.getElementById('latestOrderRecipient').textContent = latestOrder.recipientInfo.name;
            document.getElementById('latestOrderAddress').textContent = 
                `${latestOrder.recipientInfo.province} ${latestOrder.recipientInfo.city} ${latestOrder.recipientInfo.district} ${latestOrder.recipientInfo.detailAddress}`;
            document.getElementById('latestOrderTime').textContent = new Date(latestOrder.creationTime).toLocaleString();
            
            // 设置订单状态
            const statusBadge = document.getElementById('latestOrderStatus');
            statusBadge.textContent = getStatusText(latestOrder.status);
            statusBadge.className = `badge ${getStatusBadgeClass(latestOrder.status)}`;
            
            // 获取订单路径和轨迹
            const [pathResponse, traceResponse] = await Promise.all([
                fetch(`${API_BASE_URL}/orders/${latestOrder.orderNumber}/path`),
                fetch(`${API_BASE_URL}/orders/${latestOrder.orderNumber}/traces`)
            ]);
            
            // 处理路径数据
            if (pathResponse.ok) {
                const pathData = await pathResponse.json();
                if (Array.isArray(pathData) && pathData.length > 0) {
                    // 初始化地图并显示路径
                    initializeLatestOrderMap(pathData);
                } else {
                    document.getElementById('latestOrderMapContainer').innerHTML = 
                        '<div class="d-flex justify-content-center align-items-center h-100"><p class="text-muted">暂无配送路径信息</p></div>';
                }
            } else {
                document.getElementById('latestOrderMapContainer').innerHTML = 
                    '<div class="d-flex justify-content-center align-items-center h-100"><p class="text-muted">暂无配送路径信息</p></div>';
            }
        } catch (error) {
            console.error('加载最近订单时出错:', error);
        }
    }
    
    // 初始化最近订单地图
    function initializeLatestOrderMap(pathCoordinates) {
        const mapContainer = document.getElementById('latestOrderMapContainer');
        mapContainer.innerHTML = '';
        
        try {
            const map = new AMap.Map('latestOrderMapContainer', {
                resizeEnable: true,
                zoom: 11,
                center: pathCoordinates[0]
            });
            const polyline = new AMap.Polyline({
                path: pathCoordinates,
                strokeColor: "#0d6efd",
                strokeOpacity: 0.9,
                strokeWeight: 6,
                strokeStyle: "solid",
                showDir: true
            });
            map.add(polyline);
            
            if (pathCoordinates.length > 0) {
                map.add(new AMap.Marker({
                    position: new AMap.LngLat(pathCoordinates[0][0], pathCoordinates[0][1]),
                    title: '起点'
                }));
            }
            
            if (pathCoordinates.length > 1) {
                map.add(new AMap.Marker({
                    position: new AMap.LngLat(pathCoordinates[pathCoordinates.length - 1][0], pathCoordinates[pathCoordinates.length - 1][1]),
                    title: '终点'
                }));
            }
            
            map.setFitView([polyline], false, [60, 60, 60, 60], 18);
        } catch (e) {
            console.error("初始化地图出错:", e);
            mapContainer.innerHTML = '<div class="d-flex justify-content-center align-items-center h-100"><p class="text-danger">地图加载失败</p></div>';
        }
    }

    // 获取状态文本
    function getStatusText(status) {
        const statusMap = {
            'PENDING': '待处理',
            'ACCEPTED': '已接单',
            'PICKED_UP': '已取件',
            'IN_TRANSIT': '运输中',
            'DELIVERED': '已送达',
            'CANCELLED': '已取消'
            // 已删除 'PENDING_COLLECTION': '待揽收'
        };
        return statusMap[status] || status;
    }

    // 获取状态徽章样式
    function getStatusBadgeClass(status) {
        const classMap = {
            'PENDING': 'bg-secondary',
            'ACCEPTED': 'bg-info',
            'PICKED_UP': 'bg-primary',
            'IN_TRANSIT': 'bg-warning',
            'DELIVERED': 'bg-success',
            'CANCELLED': 'bg-danger'
        };
       return classMap[status] || 'bg-secondary';
    }
    
    function displayLoggedOutUI() {
        if (authLinksContainer) authLinksContainer.style.display = 'block';
        if (userDropdownContainer) userDropdownContainer.style.display = 'none';
        
        // 隐藏创建订单按钮
        if (triggerCreateOrderModalButton) triggerCreateOrderModalButton.style.display = 'none';
        
        // Consider clearing sensitive data or redirecting
        // clearQueryResults(); // If showing query results implies logged-in state
    }

    function handleLogout(event) {
        if(event) event.preventDefault();
        console.log('Attempting to logout...');
        window.location.href = '/logout'; // Redirect to Spring Security logout endpoint
    }

    // --- API Call Wrapper (Recommended for handling auth errors globally) ---
    async function fetchAuthenticatedApi(url, options = {}) {
        // You can add default headers if needed, e.g., for JWT if you switch later
        // options.headers = { ...options.headers, 'Authorization': `Bearer ${getToken()}` };

        const response = await fetch(url, options);

        if (response.status === 401) {
            // Unauthorized: Not logged in or session expired
            showAlert('会话已过期或您需要登录才能执行此操作。正在跳转到登录页面...', 'warning', true);
            setTimeout(() => {
                // Redirect to login, potentially with a redirect-back URL
                window.location.href = `/login.html?redirect=${encodeURIComponent(window.location.pathname + window.location.search)}`;
            }, 2000);
            throw new Error('Unauthorized'); // Throw to stop further processing in calling function
        }
        if (response.status === 403) {
            // Forbidden: Logged in but no permission
            showAlert('您没有权限执行此操作。', 'danger');
            throw new Error('Forbidden'); // Throw to stop further processing
        }
        return response; // Return the original response for further handling
    }


    // --- Core Application Functions (Order Tracking, Creation, Map) ---
    async function handleTrackOrder() {
        const orderNumber = orderNumberInput.value.trim();
        if (!orderNumber) { showAlert('请输入订单号!', 'warning'); return; }
        clearQueryResults();
        showLoader(true);

        try {
            // Use fetchAuthenticatedApi if these endpoints require authentication
            // For now, assuming they are public or auth handled by SecurityConfig path rules
            const orderDetailsResponse = await fetch(`${API_BASE_URL}/orders/${orderNumber}`);
            if (orderDetailsResponse.status === 401) {
                showAlert('您需要登录才能查询订单。 <a href="/login.html" class="alert-link">点此登录</a>', 'warning', true);
                showLoader(false);
                return;
            }
            if (!orderDetailsResponse.ok && orderDetailsResponse.status !== 404) { // Allow 404 to proceed to show "not found"
                const errorText = await orderDetailsResponse.text();
                showAlert(`获取订单详情失败: ${orderDetailsResponse.status} ${errorText || orderDetailsResponse.statusText}`, 'danger');
                throw new Error('Failed to fetch order details');
            }
            const orderData = orderDetailsResponse.status === 404 ? null : await orderDetailsResponse.json();
            currentOrder = orderData; // 保存当前订单到全局变量
        
            let traceData = null;
            let pathData = null;

            if (orderData) { // Only fetch traces and path if order exists
                const [traceResponse, pathResponse] = await Promise.all([
                    fetch(`${API_BASE_URL}/orders/${orderNumber}/traces`),
                    fetch(`${API_BASE_URL}/orders/${orderNumber}/path`)
                ]);

                // Trace Data
                if (traceResponse.ok) {
                    traceData = await traceResponse.json();
                } else if (traceResponse.status !== 404) { // Don't show error for 404 on traces
                    console.warn(`Failed to fetch traces: ${traceResponse.status}`);
                }


                // Path Data
                if (pathResponse.ok) {
                    const rawPathData = await pathResponse.json();
                    if (Array.isArray(rawPathData) && rawPathData.every(p => Array.isArray(p) && p.length === 2 && p.every(c => typeof c === 'number'))) {
                        pathData = rawPathData;
                    } else {
                        console.warn('Received invalid path data format:', rawPathData);
                    }
                } else if (pathResponse.status !== 404) { // Don't show error for 404 on path
                    console.warn(`Failed to fetch path: ${pathResponse.status}`);
                }
            }


            if (orderData) {
                displayOrderDetails(orderData);
                logisticsTraceAndMapColumn.style.display = 'block';
            } else {
                showAlert(`订单号 ${orderNumber} 未找到。`, 'warning');
            }

            if (traceData && traceData.length > 0) {
                displayLogisticsTraces(traceData);
            } else if (orderData) { // Order exists but no traces
                logisticsTraceCardBody.innerHTML = '<p>暂无物流追踪更新。</p>';
            }


            if (pathData && pathData.length > 0) {
                initializeAndDisplayMap(pathData);
                mapDisplaySection.style.display = 'block';
            } else if (orderData) { // Order exists but no path
                initializeAndDisplayMap(null); // 传入null，让函数处理没有路径数据的情况
                mapDisplaySection.style.display = 'block';
            }

        } catch (error) {
            // Catch errors from fetchAuthenticatedApi or other unhandled issues
            if (error.message !== 'Unauthorized' && error.message !== 'Forbidden') {
                console.error('Error during tracking:', error);
                showAlert('请先登录。', 'danger');
            }
        } finally {
            showLoader(false);
        }
    }

    async function fetchOrderDetails(orderNumber) { /* Merged into handleTrackOrder or use fetchAuthenticatedApi */ return null; }
    async function fetchLogisticsTraces(orderNumber) { /* Merged into handleTrackOrder or use fetchAuthenticatedApi */ return null; }
    async function fetchOrderPath(orderNumber) { /* Merged into handleTrackOrder or use fetchAuthenticatedApi */ return null; }


    function displayOrderDetails(order) {
        if (!order) return;
        let addressHtml = (addr, type) => { /* Your existing implementation */
            if (!addr) return `<p class="mb-1"><strong>${type}信息:</strong> N/A</p>`;
            return `<h6 class="card-subtitle mt-3 mb-1 text-muted"><i class="bi ${type === '发货方' ? 'bi-person-up' : 'bi-person-down'} me-1"></i>${type}</h6>
                        <p class="card-text mb-1 small"><strong>姓名:</strong> ${addr.name || 'N/A'}<br><strong>电话:</strong> ${addr.phone || 'N/A'}<br><strong>地址:</strong> ${addr.province || ''} ${addr.city || ''} ${addr.district || ''} ${addr.detailAddress || ''}</p>`;
        };
        orderDetailsDiv.innerHTML = `<div class="card-header bg-primary text-white d-flex justify-content-between align-items-center"><h5 class="mb-0">订单号: ${order.orderNumber || 'N/A'}</h5><span class="badge bg-light text-primary">${order.status ? formatOrderStatus(order.status) : 'N/A'}</span></div><ul class="list-group list-group-flush"><li class="list-group-item"><strong><i class="bi bi-card-text me-2"></i>物品描述:</strong> ${order.itemDescription || 'N/A'}</li><li class="list-group-item"><strong><i class="bi bi-rulers me-2"></i>重量:</strong> ${order.weight !== null ? order.weight + ' kg' : 'N/A'}</li><li class="list-group-item"><strong><i class="bi bi-cash-coin me-2"></i>计算费用:</strong> ${order.calculatedFee !== null ? '¥' + order.calculatedFee.toFixed(2) : 'N/A'}</li><li class="list-group-item"><strong><i class="bi bi-calendar-plus me-2"></i>创建时间:</strong> ${order.creationTime ? formatDate(order.creationTime) : 'N/A'}</li>${order.pickupTime ? `<li class="list-group-item"><strong><i class="bi bi-box-arrow-in-up me-2"></i>揽收时间:</strong> ${formatDate(order.pickupTime)}</li>` : ''}${order.deliveryTime ? `<li class="list-group-item"><strong><i class="bi bi-calendar-check me-2"></i>送达时间:</strong> ${formatDate(order.deliveryTime)}</li>` : ''}${order.deliveryPersonId ? `<li class="list-group-item"><strong><i class="bi bi-person-badge me-2"></i>配送员ID:</strong> ${order.deliveryPersonId}</li>` : ''}</ul><div class="card-body pt-2">${addressHtml(order.shipperInfo, '发货方')}${addressHtml(order.recipientInfo, '收货方')}</div>`;
        orderInfoColumn.style.display = 'block';
    }

    function displayLogisticsTraces(traces) {
        if (!traces) { logisticsTraceCardBody.innerHTML = '<p>无法加载物流信息。</p>'; return; }
        if (traces.length === 0) { logisticsTraceCardBody.innerHTML = '<p>暂无物流追踪更新。</p>'; return; }
        let tracesHtml = traces.map(trace => `<div class="trace-item"><div class="trace-time"><i class="bi bi-clock-history me-1"></i>${trace.timestamp ? formatDate(trace.timestamp) : '时间未知'}</div><div class="trace-description">${trace.status ? formatLogisticsStatus(trace.status) : (trace.description || '状态未知')}</div><div class="trace-details text-muted small">${trace.location ? `<i class="bi bi-geo me-1"></i>地点: ${trace.location}` : ''}${trace.operator ? `<span class="ms-2"><i class="bi bi-person-fill me-1"></i>操作员: ${trace.operator}</span>` : ''}${(trace.status && trace.description && trace.description !== formatLogisticsStatus(trace.status)) ? `<span class="ms-2"><i class="bi bi-info-circle me-1"></i>备注: ${trace.description}</span>` : (trace.description && !trace.status) ? `备注: ${trace.description}`: ''}</div></div>`).join('');
        logisticsTraceCardBody.innerHTML = tracesHtml;
    }

    function initializeAndDisplayMap(pathCoordinates) {
        if (typeof AMap === "undefined" || typeof AMap.Map === "undefined") {
            console.error("AMap SDK not loaded!");
            mapContainerDiv.innerHTML = '<p class="text-center text-danger p-3">高德地图SDK加载失败。</p>';
            mapDisplaySection.style.display = 'block';
            return;
        }
        
        if (mapInstance) { mapInstance.destroy(); mapInstance = null; }
        mapContainerDiv.innerHTML = '';
        
        try {
            // 即使没有路径数据，也创建地图实例
            mapInstance = new AMap.Map('mapContainer', {
                resizeEnable: true, zoom: 11
            });
            
            // 如果有路径数据，绘制路径
            if (pathCoordinates && pathCoordinates.length > 0) {
                const polyline = new AMap.Polyline({
                    path: pathCoordinates, strokeColor: "#0d6efd", strokeOpacity: 0.9,
                    strokeWeight: 6, strokeStyle: "solid", showDir: true
                });
                mapInstance.add(polyline);
                
                // 添加起点和终点标记
                if (pathCoordinates.length > 0) {
                    mapInstance.add(new AMap.Marker({ position: new AMap.LngLat(pathCoordinates[0][0], pathCoordinates[0][1]), title: '起点' }));
                }
                if (pathCoordinates.length > 1) {
                    mapInstance.add(new AMap.Marker({ position: new AMap.LngLat(pathCoordinates[pathCoordinates.length - 1][0], pathCoordinates[pathCoordinates.length - 1][1]), title: '终点' }));
                }
                
                mapInstance.setFitView([polyline], false, [60, 60, 60, 60], 18);
            } else {
                // 如果没有路径数据，但有订单数据，尝试使用订单的发货人和收货人地址坐标
                if (currentOrder && currentOrder.shipperInfo && currentOrder.recipientInfo) {
                    const shipperCoords = [currentOrder.shipperInfo.longitude, currentOrder.shipperInfo.latitude];
                    const recipientCoords = [currentOrder.recipientInfo.longitude, currentOrder.recipientInfo.latitude];
                    
                    // 检查坐标是否有效
                    const validShipperCoords = shipperCoords[0] && shipperCoords[1];
                    const validRecipientCoords = recipientCoords[0] && recipientCoords[1];
                    
                    if (validShipperCoords) {
                        mapInstance.add(new AMap.Marker({ position: new AMap.LngLat(shipperCoords[0], shipperCoords[1]), title: '发货点' }));
                    }
                    
                    if (validRecipientCoords) {
                        mapInstance.add(new AMap.Marker({ position: new AMap.LngLat(recipientCoords[0], recipientCoords[1]), title: '收货点' }));
                    }
                    
                    if (validShipperCoords && validRecipientCoords) {
                        // 如果两个点都有效，设置地图视图以包含两个点
                        const bounds = new AMap.Bounds(
                            [Math.min(shipperCoords[0], recipientCoords[0]), Math.min(shipperCoords[1], recipientCoords[1])],
                            [Math.max(shipperCoords[0], recipientCoords[0]), Math.max(shipperCoords[1], recipientCoords[1])]
                        );
                        mapInstance.setBounds(bounds, false, [60, 60, 60, 60]);
                    } else if (validShipperCoords) {
                        mapInstance.setCenter(new AMap.LngLat(shipperCoords[0], shipperCoords[1]));
                    } else if (validRecipientCoords) {
                        mapInstance.setCenter(new AMap.LngLat(recipientCoords[0], recipientCoords[1]));
                    } else {
                        // 如果没有任何有效坐标，显示提示信息
                        mapContainerDiv.innerHTML = '<p class="text-center p-3">暂无配送路径信息。</p>';
                    }
                } else {
                    // 如果没有任何有效坐标，显示提示信息
                    mapContainerDiv.innerHTML = '<p class="text-center p-3">暂无配送路径信息。</p>';
                }
            }
            
            mapDisplaySection.style.display = 'block';
        } catch (e) {
            console.error("Error initializing AMap:", e);
            mapContainerDiv.innerHTML = '<p class="text-center text-danger p-3">地图加载或路径绘制失败。</p>';
            mapDisplaySection.style.display = 'block';
        }
    }

    // 通过API加载省市区数据
    async function loadRegionData() {
        try {
            // 加载省份数据
            const response = await fetch(`${API_BASE_URL}/regions/provinces`);

            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const provinces = await response.json();
            // 初始化省份下拉框
            initProvinceSelect(provinces);
        } catch (error) {
            console.error('加载省市区数据失败:', error);
            // 检查是否已登录，只有登录状态才显示错误提示
            // 通过检查页面上的用户下拉菜单是否显示来判断登录状态
            if (userDropdownContainer && userDropdownContainer.style.display === 'block') {
                showAlert('加载省市区数据失败，请刷新页面重试。', 'danger');
            }
        }
    }
    
    // 初始化省份下拉框
    function initProvinceSelect(provinces) {
        const shipperProvinceSelect = document.getElementById('shipperProvinceM');
        const recipientProvinceSelect = document.getElementById('recipientProvinceM');
        
        // 清空现有选项
        shipperProvinceSelect.innerHTML = '<option value="">请选择省份</option>';
        recipientProvinceSelect.innerHTML = '<option value="">请选择省份</option>';
        
        // 添加省份选项
        provinces.forEach(province => {
            const shipperOption = document.createElement('option');
            shipperOption.value = province.code;
            shipperOption.textContent = province.name;
            shipperOption.dataset.name = province.name;
            shipperProvinceSelect.appendChild(shipperOption);
            
            const recipientOption = document.createElement('option');
            recipientOption.value = province.code;
            recipientOption.textContent = province.name;
            recipientOption.dataset.name = province.name;
            recipientProvinceSelect.appendChild(recipientOption);
        });
    }
    
    // 根据选择的省份更新城市下拉框
    async function updateCitySelect(provinceSelect, citySelect) {
        const provinceCode = provinceSelect.value;
        citySelect.innerHTML = '<option value="">请选择城市</option>';
        document.getElementById(citySelect.id.replace('City', 'District')).innerHTML = '<option value="">请选择区域</option>';
        
        if (provinceCode) {
            try {
                const response = await fetch(`${API_BASE_URL}/regions/cities/${provinceCode}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const cities = await response.json();
                
                cities.forEach(city => {
                    const option = document.createElement('option');
                    option.value = city.code;
                    option.textContent = city.name;
                    option.dataset.name = city.name;
                    citySelect.appendChild(option);
                });
            } catch (error) {
                console.error('加载城市数据失败:', error);
                showAlert('加载城市数据失败，请重试。', 'danger');
            }
        }
    }
    
    // 根据选择的城市更新区域下拉框
    async function updateDistrictSelect(provinceSelect, citySelect, districtSelect) {
        const cityCode = citySelect.value;
        districtSelect.innerHTML = '<option value="">请选择区域</option>';
        
        if (cityCode) {
            try {
                const response = await fetch(`${API_BASE_URL}/regions/districts/${cityCode}`);
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }
                const districts = await response.json();
                
                districts.forEach(district => {
                    const option = document.createElement('option');
                    option.value = district.code;
                    option.textContent = district.name;
                    option.dataset.name = district.name;
                    districtSelect.appendChild(option);
                });
            } catch (error) {
                console.error('加载区域数据失败:', error);
                showAlert('加载区域数据失败，请重试。', 'danger');
            }
        }
    }
    
    // 设置事件监听器
    function setupRegionSelectors() {
        const shipperProvinceSelect = document.getElementById('shipperProvinceM');
        const shipperCitySelect = document.getElementById('shipperCityM');
        const shipperDistrictSelect = document.getElementById('shipperDistrictM');
        
        const recipientProvinceSelect = document.getElementById('recipientProvinceM');
        const recipientCitySelect = document.getElementById('recipientCityM');
        const recipientDistrictSelect = document.getElementById('recipientDistrictM');
        
        // 发货人省份变化时更新城市
        shipperProvinceSelect.addEventListener('change', () => {
            updateCitySelect(shipperProvinceSelect, shipperCitySelect);
        });
        
        // 发货人城市变化时更新区域
        shipperCitySelect.addEventListener('change', () => {
            updateDistrictSelect(shipperProvinceSelect, shipperCitySelect, shipperDistrictSelect);
        });
        
        // 收货人省份变化时更新城市
        recipientProvinceSelect.addEventListener('change', () => {
            updateCitySelect(recipientProvinceSelect, recipientCitySelect);
        });
        
        // 收货人城市变化时更新区域
        recipientCitySelect.addEventListener('change', () => {
            updateDistrictSelect(recipientProvinceSelect, recipientCitySelect, recipientDistrictSelect);
        });
    }
    
    // 在页面加载完成后加载省市区数据并设置事件监听器
    document.addEventListener('DOMContentLoaded', () => {
        // 加载省市区数据
        let currentOrder = null;
        loadRegionData();
        
        // 设置事件监听器
        setupRegionSelectors();
        
        // 其他现有的DOMContentLoaded事件处理代码...
    });

    // 加载用户常用地址
    async function loadUserAddresses() {
        try {
            const response = await fetch(`${API_BASE_URL}/addresses/me`);
            if (!response.ok) {
                console.warn('获取常用地址失败:', response.status);
                return [];
            }
            
            const addresses = await response.json();
            console.log('获取到常用地址:', addresses);
            return addresses;
        } catch (error) {
            console.error('加载常用地址时出错:', error);
            return [];
        }
    }

    // 保存常用地址
    async function saveUserAddress(addressType) {
        try {
            // 根据类型获取地址信息
            let addressData;
            if (addressType === 'shipper') {
                addressData = {
                    name: document.getElementById('shipperNameM').value.trim(),
                    phone: document.getElementById('shipperPhoneM').value.trim(),
                    province: document.getElementById('shipperProvinceM').value.trim(),
                    city: document.getElementById('shipperCityM').value.trim(),
                    district: document.getElementById('shipperDistrictM').value.trim(),
                    detailAddress: document.getElementById('shipperDetailAddressM').value.trim()
                };
            } else {
                addressData = {
                    name: document.getElementById('recipientNameM').value.trim(),
                    phone: document.getElementById('recipientPhoneM').value.trim(),
                    province: document.getElementById('recipientProvinceM').value.trim(),
                    city: document.getElementById('recipientCityM').value.trim(),
                    district: document.getElementById('recipientDistrictM').value.trim(),
                    detailAddress: document.getElementById('recipientDetailAddressM').value.trim(),
                    email: document.getElementById('recipientEmailM').value.trim() || null,
                    emailNotificationEnabled: document.getElementById('recipientEmailNotificationM').checked
                };
            }
            
            const response = await fetch(`${API_BASE_URL}/addresses/me`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(addressData)
            });
            
            if (response.ok) {
                alert('地址已保存到常用地址');
                return true;
            } else {
                console.warn('保存常用地址失败:', response.status);
                return false;
            }
        } catch (error) {
            console.error('保存常用地址时出错:', error);
            return false;
        }
    }

    // 填充地址表单
    function fillAddressForm(address, type) {
        if (type === 'shipper') {
            document.getElementById('shipperNameM').value = address.name || '';
            document.getElementById('shipperPhoneM').value = address.phone || '';
            document.getElementById('shipperProvinceM').value = address.province || '';
            document.getElementById('shipperCityM').value = address.city || '';
            document.getElementById('shipperDistrictM').value = address.district || '';
            document.getElementById('shipperDetailAddressM').value = address.detailAddress || '';
        } else {
            document.getElementById('recipientNameM').value = address.name || '';
            document.getElementById('recipientPhoneM').value = address.phone || '';
            document.getElementById('recipientProvinceM').value = address.province || '';
            document.getElementById('recipientCityM').value = address.city || '';
            document.getElementById('recipientDistrictM').value = address.district || '';
            document.getElementById('recipientDetailAddressM').value = address.detailAddress || '';
            document.getElementById('recipientEmailM').value = address.email || '';
            document.getElementById('recipientEmailNotificationM').checked = address.emailNotificationEnabled || false;
        }
    }

    // 显示常用地址选择下拉菜单
    async function showAddressSelector(type) {
        const addresses = await loadUserAddresses();
        if (!addresses || addresses.length === 0) {
            alert('没有保存的常用地址');
            return;
        }
        
        // 创建下拉菜单
        let selectHtml = '<select class="form-select" id="addressSelector">';
        selectHtml += '<option value="" selected>选择一个地址...</option>';
        
        addresses.forEach(address => {
            const addressText = `${address.name} - ${address.province}${address.city}${address.district}${address.detailAddress}`;
            selectHtml += `<option value="${address.id}">${addressText}</option>`;
        });
        
        selectHtml += '</select>';
        
        // 显示模态框
        const modalHtml = `
        <div class="modal fade" id="addressSelectorModal" tabindex="-1" aria-hidden="true">
            <div class="modal-dialog">
                <div class="modal-content">
                    <div class="modal-header">
                        <h5 class="modal-title">选择常用地址</h5>
                        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                    </div>
                    <div class="modal-body">
                        ${selectHtml}
                    </div>
                    <div class="modal-footer">
                        <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                        <button type="button" class="btn btn-primary" id="selectAddressBtn">选择</button>
                    </div>
                </div>
            </div>
        </div>
        `;
        
        // 添加到DOM
        const modalContainer = document.createElement('div');
        modalContainer.innerHTML = modalHtml;
        document.body.appendChild(modalContainer);
        
        // 显示模态框
        const modal = new bootstrap.Modal(document.getElementById('addressSelectorModal'));
        modal.show();
        
        // 处理选择按钮点击
        document.getElementById('selectAddressBtn').addEventListener('click', () => {
            const selectedId = document.getElementById('addressSelector').value;
            if (!selectedId) {
                alert('请选择一个地址');
                return;
            }
            
            const selectedAddress = addresses.find(addr => addr.id === selectedId);
            if (selectedAddress) {
                fillAddressForm(selectedAddress, type);
                modal.hide();
                // 移除模态框
                document.getElementById('addressSelectorModal').remove();
            }
        });
        
        // 处理模态框关闭事件
        document.getElementById('addressSelectorModal').addEventListener('hidden.bs.modal', () => {
            document.getElementById('addressSelectorModal').remove();
        });
    }

    // 修改handleCreateOrder函数，使其适配下拉选择框
    async function handleCreateOrder(event) {
        event.preventDefault(); 
        clearAlert();
        
        // 获取省市区下拉框元素
        const shipperProvinceSelect = document.getElementById('shipperProvinceM');
        const shipperCitySelect = document.getElementById('shipperCityM');
        const shipperDistrictSelect = document.getElementById('shipperDistrictM');

        const recipientProvinceSelect = document.getElementById('recipientProvinceM');
        const recipientCitySelect = document.getElementById('recipientCityM');
        const recipientDistrictSelect = document.getElementById('recipientDistrictM');

        // 获取选中选项的名称
        const shipperProvinceName = shipperProvinceSelect.options[shipperProvinceSelect.selectedIndex].dataset.name;
        const shipperCityName = shipperCitySelect.options[shipperCitySelect.selectedIndex].dataset.name;
        const shipperDistrictName = shipperDistrictSelect.options[shipperDistrictSelect.selectedIndex].dataset.name;

        const recipientProvinceName = recipientProvinceSelect.options[recipientProvinceSelect.selectedIndex].dataset.name;
        const recipientCityName = recipientCitySelect.options[recipientCitySelect.selectedIndex].dataset.name;
        const recipientDistrictName = recipientDistrictSelect.options[recipientDistrictSelect.selectedIndex].dataset.name;
        
        const orderDataPayload = {
            shipperInfo: {
                name: document.getElementById('shipperNameM').value.trim(),
                phone: document.getElementById('shipperPhoneM').value.trim(),
                province: shipperProvinceName,
                city: shipperCityName,
                district: shipperDistrictName,
                detailAddress: document.getElementById('shipperDetailAddressM').value.trim()
            },
            recipientInfo: {
                name: document.getElementById('recipientNameM').value.trim(),
                phone: document.getElementById('recipientPhoneM').value.trim(),
                province: recipientProvinceName,
                city: recipientCityName,
                district: recipientDistrictName,
                detailAddress: document.getElementById('recipientDetailAddressM').value.trim(),
                email: document.getElementById('recipientEmailM').value.trim() || null,
                emailNotificationEnabled: document.getElementById('recipientEmailNotificationM').checked
            },
            itemDescription: document.getElementById('itemDescriptionM').value.trim(),
            weight: parseFloat(document.getElementById('weightM').value)
        };
        
        if (!orderDataPayload.shipperInfo.name || !orderDataPayload.shipperInfo.phone || !orderDataPayload.shipperInfo.province || !orderDataPayload.shipperInfo.city || !orderDataPayload.shipperInfo.detailAddress || !orderDataPayload.recipientInfo.name || !orderDataPayload.recipientInfo.phone || !orderDataPayload.recipientInfo.province || !orderDataPayload.recipientInfo.city || !orderDataPayload.recipientInfo.detailAddress || !orderDataPayload.itemDescription || isNaN(orderDataPayload.weight) || orderDataPayload.weight <= 0) {
            showAlert('请填写所有必填项，并确保重量有效。', 'danger'); return;
        }
    
        showLoader(true);
        try {
            // Use the fetchAuthenticatedApi wrapper for calls that need authentication
            const response = await fetchAuthenticatedApi(`${API_BASE_URL}/orders`, { // Changed to use the wrapper
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(orderDataPayload),
            });
            
            if (response.ok && response.status === 201) { // Check for 201 Created
                const createdOrder = await response.json();
                createOrderModalInstance.hide();
                showAlert(`订单 ${createdOrder.orderNumber} 创建成功!`, 'success');
                orderNumberInput.value = createdOrder.orderNumber; // Optionally prefill for immediate tracking
                handleTrackOrder(); // Optionally track the newly created order
            } else if (response.ok) { // Other 2xx success but not 201 (should ideally be 201)
                const responseData = await response.json(); // Or .text()
                showAlert(`订单创建可能已成功，但服务器返回非预期成功状态: ${response.status}`, 'warning');
                console.warn('Create order unexpected success:', responseData);
            }
            // Non-OK responses (like 400 Bad Request for validation) are handled if not caught by fetchAuthenticatedApi
            else if (!response.ok && response.status !== 401 && response.status !== 403) {
                const errorResponse = await response.text(); // Or .json() if backend sends JSON error
                showAlert(`创建订单失败: ${response.status} - ${errorResponse || '未知服务器错误'}`, 'danger');
                console.error('Create order error response:', errorResponse);
            }
        } catch (error) {
            // Errors like 'Unauthorized' or 'Forbidden' are thrown by fetchAuthenticatedApi
            // and will be caught here, but showAlert for them is already handled inside the wrapper.
            // So, only log other types of errors.
            if (error.message !== 'Unauthorized' && error.message !== 'Forbidden') {
                console.error('Create order network/fetch error:', error);
                showAlert('创建订单时发生网络错误或无法连接到服务器。', 'danger');
            }
        } finally {
            showLoader(false);
        }
    }

    /**
     * 初始化邮箱选择功能
     */
    async function initializeEmailSelection() {
        const emailSelect = document.getElementById('recipientEmailSelect');
        const emailInput = document.getElementById('recipientEmailM');
        const selectedEmailDisplay = document.getElementById('selectedEmailDisplay');
        const displayEmailInput = document.getElementById('displayEmailInput');
        const changeEmailBtn = document.getElementById('changeEmailBtn');
        
        if (!emailSelect || !emailInput || !selectedEmailDisplay || !displayEmailInput || !changeEmailBtn) {
            console.warn('邮箱选择元素未找到');
            return;
        }
        
        // 加载用户保存的邮箱地址
        await loadSavedEmails();
        
        // 监听下拉选择变化
        emailSelect.addEventListener('change', function() {
            const selectedValue = this.value;
            
            if (selectedValue === 'manual') {
                // 显示手动输入框
                emailSelect.style.display = 'none';
                selectedEmailDisplay.style.display = 'none';
                emailInput.style.display = 'block';
                emailInput.value = '';
                emailInput.readOnly = false;
                emailInput.focus();
            } else if (selectedValue === '') {
                // 重置所有显示
                emailSelect.style.display = 'block';
                selectedEmailDisplay.style.display = 'none';
                emailInput.style.display = 'none';
                emailInput.value = '';
            } else {
                // 选择了保存的邮箱，显示优化的界面
                emailSelect.style.display = 'none';
                selectedEmailDisplay.style.display = 'block';
                emailInput.style.display = 'none';
                displayEmailInput.value = selectedValue;
                emailInput.value = selectedValue; // 保持隐藏输入框的值同步
            }
        });
        
        // 更换邮箱按钮事件
        changeEmailBtn.addEventListener('click', function() {
            emailSelect.style.display = 'block';
            selectedEmailDisplay.style.display = 'none';
            emailInput.style.display = 'none';
            emailSelect.value = '';
            emailInput.value = '';
        });
    }
    
    /**
     * 加载用户保存的邮箱地址到下拉选择框
     */
    async function loadSavedEmails() {
        try {
            const addresses = await loadUserAddresses();
            const emailSelect = document.getElementById('recipientEmailSelect');
            
            if (!emailSelect) return;
            
            // 清除现有选项（保留默认选项）
            const defaultOptions = emailSelect.querySelectorAll('option[value=""], option[value="manual"]');
            emailSelect.innerHTML = '';
            defaultOptions.forEach(option => emailSelect.appendChild(option));
            
            // 添加保存的邮箱选项
            if (addresses && addresses.length > 0) {
                const emailsWithEmail = addresses.filter(addr => addr.email && addr.email.trim() !== '');
                
                emailsWithEmail.forEach(address => {
                    const option = document.createElement('option');
                    option.value = address.email;
                    option.textContent = address.email;
                    emailSelect.insertBefore(option, emailSelect.querySelector('option[value="manual"]'));
                });
            }
        } catch (error) {
            console.error('加载保存的邮箱失败:', error);
        }
    }
</script>

<!-- 在container-main div中添加以下内容 -->
<section id="latestOrderSection" class="mb-5 mt-5" style="display: none;">
    <h2 class="section-title"><i class="bi bi-clock-history"></i>我的最近订单</h2>
    <div class="row g-4">
        <div class="col-lg-5">
            <div id="latestOrderDetails" class="card">
                <div class="card-body">
                    <div class="d-flex justify-content-between align-items-center mb-3">
                        <h5 class="card-title mb-0">订单详情</h5>
                        <!-- 隐藏状态标签 -->
                        <span class="badge bg-primary" id="latestOrderStatus" style="display: none;">状态</span>
                    </div>
                    <p class="card-text"><strong>订单号：</strong><span id="latestOrderNumber"></span></p>
                    <p class="card-text"><strong>物品描述：</strong><span id="latestOrderDescription"></span></p>
                    <p class="card-text"><strong>收件人：</strong><span id="latestOrderRecipient"></span></p>
                    <p class="card-text"><strong>收件地址：</strong><span id="latestOrderAddress"></span></p>
                    <p class="card-text"><strong>创建时间：</strong><span id="latestOrderTime"></span></p>
                </div>
            </div>
        </div>
        <div class="col-lg-7">
            <div class="card">
                <div class="card-body p-0">
                    <div id="latestOrderMapContainer" style="height: 350px;"></div>
                </div>
            </div>
        </div>
    </div>
</section>
</body>
</html>